import requests
from bs4 import BeautifulSoup

def getrate():
    # URL
    url = "https://www.x-rates.com/table/?from=USD&amount=1"
    items=[]
    # 发送GET请求
    response = requests.get(url)

    # 检查请求是否成功
    if response.status_code == 200:
        # 使用BeautifulSoup解析页面
        soup = BeautifulSoup(response.content, 'html.parser')

        # 找到汇率表tablesorter ratesTable
        table = soup.find('table', {'class': 'tablesorter ratesTable'})

        # 提取每一行的数据（从第二行开始，第一行是表头）
        rows = table.find_all('tr')[1:]  # 排除表头

        for row in rows:
            cols = row.find_all('td')
            if len(cols) > 1:  # 确保该行包含有效的列
                currency = cols[0].text.strip()
                exchange_rate = cols[1].text.strip()
                items.append({'currency':currency,'exchange_rate':exchange_rate})
                print(f"Currency: {currency}, Exchange Rate: {exchange_rate}")
    else:
        print("Failed to retrieve data")
    return items
# items=getrate()